package com.ai.smlcore.control.remote.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.ai.common.xml.util.ControlConstants;
import com.ai.frame.bean.InputObject;
import com.ai.frame.bean.OutputObject;
import com.ai.frame.logger.Logger;
import com.ai.frame.logger.LoggerFactory;
import com.ai.frame.util.JsonUtil;
import com.ai.smlcore.control.remote.IRemoteService;
import com.ai.smlcore.util.StringUtil;
import com.ai.smlcore.util.ThreadLocalParam;
import com.alibaba.fastjson.JSON;

/**
 */
public class BaseRemoteSVImpl implements IRemoteService {
	private com.ai.frame.IControlService controlService;
	private static final Logger logger = LoggerFactory.getServiceLog(BaseRemoteSVImpl.class);

	public void execute(InputObject inputObject, OutputObject outputObject) {
		long start = System.currentTimeMillis();

		String logParam = null;
		String id = UUID.randomUUID().toString();
		try {
			Map<String, String> logMap = ThreadLocalParam.getThreadInstance().getLogParam();
			if (logMap == null) {
				logMap = new HashMap<String, String>();
			} else if (StringUtil.isEmpty(logMap.get("OP_REQST_NO"))) {
				logMap.put("OP_REQST_NO", "");
			}
			inputObject.setLogParams(logMap);
			logParam = "OP_REQST_NO=" + id + ",service=" + inputObject.getService() + ",method="
					+ inputObject.getMethod() + ",params=" + JSON.toJSONString(inputObject.getParams());
			logger.info("START INVOKE CORE...", logParam);
			// 转换成Json
			String json = JsonUtil.inputObject2Json(inputObject);
			// 调用WebApp服务
			String result = controlService.execute(json);
			// 转换成统一输出对象
			OutputObject obj = JsonUtil.json2OutputObject(result);
			outputObject.setBean(obj.getBean());
			outputObject.setBeans(obj.getBeans());
			outputObject.setObject(obj.getObject());
			outputObject.setReturnCode(obj.getReturnCode());
			outputObject.setReturnMessage(obj.getReturnMessage());
			long end = System.currentTimeMillis();
			if (StringUtil.isNotEmpty(inputObject.getMethod()) && (inputObject.getMethod().startsWith("get")
					|| inputObject.getMethod().startsWith("query") || inputObject.getMethod().startsWith("select"))) {
				logger.info("INVOKE CORE SECCESS!", id + ", COST=" + (end - start) + "ms");
			} else {
				logger.info("INVOKE CORE SECCESS!", id + ", result=" + result + ", COST=" + (end - start) + "ms");
			}
		} catch (Exception e) {
			logger.error("INVOKE CORE ERROR!", id, e);
			outputObject.setReturnCode(ControlConstants.RETURN_CODE.SYSTEM_ERROR);
			outputObject.setReturnMessage("服务调用异常,请稍后再试!");
		}
	}

	public com.ai.frame.IControlService getControlService() {
		return controlService;
	}

	public void setControlService(com.ai.frame.IControlService controlService) {
		this.controlService = controlService;
	}
}
